﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Breath : MonoBehaviour
{
    //SightTarget动画控制器
    public Animator sightTargetAnimator;
    //当前心率
    float heartRate;
    //最低心率
    public float minRate;
    //紧张心率
    public float nervousRate;
    //最大心率
    public float maxRate;
    //屏息心率增长速度
    public float increaseNum;
    //心率恢复速度
    public float resumeNum;
    //是否正在屏息
    bool isHolding = false;
    //累计时间
    float cumulativeTime = 0;
    //静息呼吸间隔
    public float normalBreathTime;
    //紧张呼吸间隔
    public float nervousBreathTime;
    //心跳Text
    public Text heartRateText;
    //呼吸Autio
    public AudioSource breathNormalAudio;
    //急促呼吸Audio
    public AudioSource breathNervousAudio;
    // Start is called before the first frame update
    void Start()
    {
        heartRate = minRate;
        //启动呼吸控制器
        StartCoroutine(breathControl());
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (isHolding)
        {
            if (heartRate < maxRate)
                heartRate += increaseNum;
            if (heartRate > maxRate)
                heartRate = maxRate;
            if (heartRate == maxRate)
                isHolding = false;
        }
        else
        {
            if (heartRate > minRate)
                heartRate -= resumeNum;
            if (heartRate < minRate)
                heartRate = minRate;
        }
        heartRateText.text = "心跳：" + (int)heartRate;
    }

    //屏息
    public void holdBreath()
    {
        if(heartRate < nervousRate)
        {
            isHolding = true;
        }
    }

    //停止屏息
    public void cancleHoldBreath() {
        isHolding = false;
    }

    //根据心率控制呼吸
    IEnumerator breathControl()
    {
        yield return new WaitForSeconds(normalBreathTime);
        while (true)
        {
            //如果正在屏息，不触发呼吸动画
            if (!isHolding)
            {
                //最小心率与紧张心率之间，为正常状态
                if (minRate <= heartRate && heartRate <= nervousRate)
                {
                    breathNormalAudio.Play();
                    sightTargetAnimator.SetTrigger("breath");
                    yield return new WaitForSeconds(normalBreathTime);
                }
                //紧张心率与最大之间，为紧张状态
                else if (nervousRate < heartRate && heartRate <= maxRate)
                {
                    breathNervousAudio.Play();
                    sightTargetAnimator.SetTrigger("breathNervous");
                    yield return new WaitForSeconds(nervousBreathTime);
                }
                else
                {
                    throw new System.Exception("心率数据错误！");
                }

            }
            else
            {
                yield return 0;
            }
        }
    }
}
